import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { SharedModule } from '../../shared/shared.module';
import { RouterModule } from '@angular/router';
import { PagedResultDto } from '@abp/ng.core';
import { ExcelExportService } from '../../shared/services/excel-export.service';

// 批次关联数据接口
interface HuoPinPiCiGuanLianDto {
  id: number;
  serialNumber: number;
  goodsCode: string;
  goodsName: string;
  status: string;
  goodsType: string;
  specification: string;
  unit: string;
  warehouseName: string;
  locationName: string;
  goodsBarcode: string;
  currentStock: number;
  batchNumber: string;
  productionDate: string;
  expiryDate: string;
  shelfLife: number;
  remainingDays: number;
  warnDays: number;
}

// 查询参数接口
interface QueryParams {
  GoodsCodeOrName?: string;
  BatchNumber?: string;
  WarehouseName?: string;
  ExpirationDateStart?: string;
  ExpirationDateEnd?: string;
  Status?: string;
  SkipCount: number;
  MaxResultCount: number;
  Sorting?: string;
}

@Component({
  selector: 'app-bao-zhi-qi-cha-xun',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    SharedModule,
    RouterModule
  ],
  templateUrl: './bao-zhi-qi-cha-xun.component.html',
  styleUrls: ['./bao-zhi-qi-cha-xun.component.scss']
})
export class BaoZhiQiChaXunComponent implements OnInit {
  // 使Math可在模板中访问
  Math = Math;
  
  // 查询参数
  queryParams: QueryParams = {
    SkipCount: 0,
    MaxResultCount: 10,
    Sorting: ''
  };

  // 日期范围
  dateRange: { start: string, end: string } = {
    start: '',
    end: ''
  };

  // 页码和页大小设置
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  pageSizeOptions = [10, 20, 30, 50];
  inputPageNumber = 1;
  
  // 最大页数
  get maxPageCount(): number {
    return Math.ceil(this.total / this.pageSize) || 1;
  }

  // 批次数据
  dataList: HuoPinPiCiGuanLianDto[] = [];
  
  // 下拉选项 - 将从表格数据中提取
  warehouseOptions: string[] = [];
  statusOptions: string[] = [];
  
  // 状态颜色映射
  statusColorMap = {
    '正常': 'success',
    '即将过期': 'warning',
    '已过期': 'danger'
  };
  
  loading = false;
  apiError = false;
  errorMessage = '';
  today = new Date();
  
  // 日期筛选默认值
  defaultStartDate = new Date();
  defaultEndDate = new Date();

  // 导出状态
  exporting = false;
  
  constructor(private http: HttpClient, private excelExportService: ExcelExportService) {
    // 初始化空日期范围
    this.dateRange = {
      start: '',
      end: ''
    };
    
    // 设置查询参数中的日期为空
    this.queryParams.ExpirationDateStart = '';
    this.queryParams.ExpirationDateEnd = '';
  }

  ngOnInit(): void {
    console.log('组件初始化，日期范围:', this.dateRange);
    // 加载数据
    this.loadData();
    
    // 初始化静态状态选项，以防API调用前需要显示
    this.statusOptions = ['正常', '即将过期', '已过期'];
  }
  
  // 从表格数据中提取选项
  extractOptionsFromData(): void {
    // 提取仓库名称选项（去重）
    this.warehouseOptions = [...new Set(this.dataList.map(item => item.warehouseName))].filter(Boolean);
    
    // 提取状态选项（去重）
    this.statusOptions = [...new Set(this.dataList.map(item => item.status))].filter(Boolean);
    
    // 对选项进行排序
    this.warehouseOptions.sort();
    this.statusOptions.sort((a, b) => {
      // 自定义排序: '正常' -> '即将过期' -> '已过期'
      const order = { '正常': 1, '即将过期': 2, '已过期': 3 };
      return (order[a] || 99) - (order[b] || 99);
    });
  }

  // 处理日期范围变化
  onDateRangeChange(): void {
    // 更新查询参数中的日期
    this.queryParams.ExpirationDateStart = this.dateRange.start || '';
    this.queryParams.ExpirationDateEnd = this.dateRange.end || '';
    
    console.log('日期范围已更新:', this.dateRange);
    console.log('查询参数已更新:', this.queryParams);
  }
  
  // 格式化日期为YYYY-MM-DD
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  
  // 计算剩余天数
  calculateRemainingDays(expirationDate: string): number {
    if (!expirationDate) return 0;
    
    const expDate = new Date(expirationDate);
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 重置时间为当天开始
    
    const diffTime = expDate.getTime() - today.getTime();
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  }
  
  // 获取状态
  getStatus(remainingDays: number): string {
    if (remainingDays > 30) return '正常';
    if (remainingDays >= 0) return '即将过期';
    return '已过期';
  }
  
  // 检查是否匹配所选状态
  matchesStatus(remainingDays: number, selectedStatus: string | null): boolean {
    if (!selectedStatus) return true; // 如果没有选择状态，则匹配所有记录
    
    const status = this.getStatus(remainingDays);
    return status === selectedStatus;
  }

  // 重置筛选条件
  reset(): void {
    // 重置日期范围为空
    this.dateRange = {
      start: '',
      end: ''
    };
    
    this.queryParams = {
      SkipCount: 0,
      MaxResultCount: this.pageSize,
      Sorting: '',
      ExpirationDateStart: '',
      ExpirationDateEnd: '',
      Status: null // 重置状态为null
    };
    this.pageIndex = 1;
    this.loadData();
  }

  // 加载数据
  loadData(): void {
    this.loading = true;
    this.apiError = false;
    
    // 确保页码正确
    this.queryParams.SkipCount = (this.pageIndex - 1) * this.pageSize;
    this.queryParams.MaxResultCount = this.pageSize;
    
    // 再次确保日期参数从dateRange获取最新值
    this.queryParams.ExpirationDateStart = this.dateRange.start || '';
    this.queryParams.ExpirationDateEnd = this.dateRange.end || '';
    
    console.log('加载数据时的日期范围:', this.dateRange);
    console.log('加载数据时的查询参数:', this.queryParams);
    
    const apiUrl = 'https://localhost:44359/api/app/huo-pin-pi-ci-guan-lian';
    
    // 创建HttpParams对象
    let params = new HttpParams();
    
    // 添加查询参数（但不添加Status，我们会在前端手动过滤）
    Object.keys(this.queryParams).forEach(key => {
      const value = this.queryParams[key as keyof QueryParams];
      if (value !== undefined && value !== null && value !== '' && key !== 'Status') {
        params = params.set(key, String(value));
      }
    });
    
    console.log('发送请求参数:', params.toString());
    console.log('选择的状态:', this.queryParams.Status);
    console.log('日期范围:', this.dateRange);
    
    this.http.get<PagedResultDto<HuoPinPiCiGuanLianDto>>(apiUrl, { params })
      .subscribe({
        next: (response) => {
          console.log('API返回数据:', response);
          if (response && response.items) {
            let allItems = response.items.map(item => {
              const remainingDays = this.calculateRemainingDays(item.expiryDate);
              const status = this.getStatus(remainingDays);
              return {
                ...item,
                remainingDays: remainingDays,
                status: status
              };
            });
            
            // 手动应用日期过滤
            if (this.dateRange.start || this.dateRange.end) {
              console.log('应用日期过滤...');
              const startDate = this.dateRange.start ? new Date(this.dateRange.start) : null;
              const endDate = this.dateRange.end ? new Date(this.dateRange.end) : null;
              
              if (startDate) startDate.setHours(0, 0, 0, 0);
              if (endDate) endDate.setHours(23, 59, 59, 999);
              
              allItems = allItems.filter(item => {
                const itemDate = new Date(item.expiryDate);
                let matchesFilter = true;
                
                if (startDate && itemDate < startDate) {
                  matchesFilter = false;
                }
                
                if (endDate && itemDate > endDate) {
                  matchesFilter = false;
                }
                
                return matchesFilter;
              });
              
              console.log(`日期过滤后剩余记录: ${allItems.length}`);
            }
            
            const totalBeforeFilter = allItems.length;
            
            // 如果设置了状态过滤，手动过滤数据
            if (this.queryParams.Status) {
              console.log(`根据状态 "${this.queryParams.Status}" 过滤数据...`);
              allItems = allItems.filter(item => item.status === this.queryParams.Status);
              console.log(`过滤前: ${totalBeforeFilter} 条记录, 过滤后: ${allItems.length} 条记录`);
            }
            
            this.dataList = allItems;
            this.total = response.totalCount; // 保持原有总数
            
            // 从数据中提取选项
            this.extractOptionsFromData();
          }
          this.loading = false;
        },
        error: (error: HttpErrorResponse) => {
          console.error('获取保质期数据失败:', error);
          this.loading = false;
          this.apiError = true;
          
          if (error.status === 0) {
            this.errorMessage = '网络错误或CORS问题，请检查网络连接和后端CORS配置';
          } else {
            this.errorMessage = `获取数据失败: ${error.status} ${error.statusText}`;
            if (error.error && error.error.error) {
              this.errorMessage += ` - ${error.error.error.message || '未知错误'}`;
            }
          }
          
          // 使用模拟数据
          this.mockData();
        }
      });
  }
  
  // 模拟数据
  mockData(): void {
    const mockItems: HuoPinPiCiGuanLianDto[] = [];
    
    // 生成更多数据，确保每种状态都有足够的项目
    for (let i = 1; i <= 30; i++) {
      const manufactureDate = new Date();
      manufactureDate.setDate(manufactureDate.getDate() - 180); // 生产日期在6个月前
      
      const expirationDate = new Date();
      
      // 根据索引设置不同的过期日期：正常，即将过期，已过期
      if (i <= 10) {
        // 正常：设置为60天后过期
        expirationDate.setDate(expirationDate.getDate() + 60 + i * 10);
      } else if (i <= 20) {
        // 即将过期：设置为15天后过期
        expirationDate.setDate(expirationDate.getDate() + 15 + (i - 10));
      } else {
        // 已过期：设置为过去的日期
        expirationDate.setDate(expirationDate.getDate() - (i - 20) * 5);
      }
      
      const goodsCode = `HPDH${String(Math.floor(Math.random() * 10000)).padStart(4, '0')}`;
      const goodsTypes = ['电器', '食品', '服装', '化妆品', '办公用品'];
      
      const remainingDays = this.calculateRemainingDays(this.formatDate(expirationDate));
      const status = this.getStatus(remainingDays);
      
      // 使用实际数据中的仓库名称
      const warehouseNames = ['主仓库', '办公仓库', '食品仓库', 'C区-03', 'B区-02', 'A区-01'];
      
      mockItems.push({
        id: i,
        serialNumber: i,
        goodsCode: goodsCode,
        goodsName: `测试商品${i}`,
        status: status,
        goodsType: goodsTypes[i % goodsTypes.length],
        specification: `规格${i}`,
        unit: '个',
        warehouseName: warehouseNames[i % warehouseNames.length],
        locationName: `${String.fromCharCode(65 + (i % 5))}区`,
        goodsBarcode: `BARCODE${String(Math.floor(Math.random() * 1000000)).padStart(6, '0')}`,
        currentStock: 50 + i * 10,
        batchNumber: `BN${String(2025070700 + i)}`,
        productionDate: this.formatDate(manufactureDate),
        expiryDate: this.formatDate(expirationDate),
        shelfLife: 365, // 模拟货架期
        remainingDays: remainingDays,
        warnDays: 10 // 模拟预警天数
      });
    }
    
    let filteredItems = [...mockItems];
    
    // 手动应用日期过滤
    if (this.dateRange.start || this.dateRange.end) {
      console.log('应用日期过滤到模拟数据...');
      const startDate = this.dateRange.start ? new Date(this.dateRange.start) : null;
      const endDate = this.dateRange.end ? new Date(this.dateRange.end) : null;
      
      if (startDate) startDate.setHours(0, 0, 0, 0);
      if (endDate) endDate.setHours(23, 59, 59, 999);
      
      filteredItems = filteredItems.filter(item => {
        const itemDate = new Date(item.expiryDate);
        let matchesFilter = true;
        
        if (startDate && itemDate < startDate) {
          matchesFilter = false;
        }
        
        if (endDate && itemDate > endDate) {
          matchesFilter = false;
        }
        
        return matchesFilter;
      });
      
      console.log(`日期过滤后模拟记录数: ${filteredItems.length}`);
    }
    
    const totalBeforeFilter = filteredItems.length;
    
    // 如果设置了状态过滤，手动过滤数据
    if (this.queryParams.Status) {
      console.log(`根据状态 "${this.queryParams.Status}" 过滤模拟数据...`);
      filteredItems = filteredItems.filter(item => item.status === this.queryParams.Status);
      console.log(`过滤前: ${totalBeforeFilter} 条记录, 过滤后: ${filteredItems.length} 条记录`);
    }
    
    this.dataList = filteredItems;
    this.total = 100; // 假设总共有100条数据
    
    // 从数据中提取选项
    this.extractOptionsFromData();
  }

  // 页码变更
  pageIndexChange(index: number): void {
    if (index < 1 || index > this.maxPageCount) {
      return;
    }
    this.pageIndex = index;
    this.inputPageNumber = index;
    this.loadData();
  }

  // 页大小变更
  pageSizeChange(size: number): void {
    this.pageSize = Number(size);
    this.pageIndex = 1;
    this.loadData();
  }
  
  // 处理页码输入变化
  onPageInputChange(event: any): void {
    let page = parseInt(event.target.value);
    if (isNaN(page)) {
      page = 1;
    }
    if (page < 1) {
      page = 1;
    }
    if (page > this.maxPageCount) {
      page = this.maxPageCount;
    }
    this.inputPageNumber = page;
  }
  
  // 处理页码输入回车
  onPageInputKeyUp(event: KeyboardEvent): void {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }
  
  // 跳转到指定页
  goToPage(page: number): void {
    this.pageIndexChange(page);
  }

  // 搜索
  search(): void {
    console.log("执行搜索...");
    console.log("日期范围:", this.dateRange);
    console.log("查询参数:", this.queryParams);
    
    // 更新查询参数中的日期
    this.queryParams.ExpirationDateStart = this.dateRange.start || '';
    this.queryParams.ExpirationDateEnd = this.dateRange.end || '';
    
    // 重置页码到第一页
    this.pageIndex = 1;
    
    // 加载数据
    this.loadData();
  }
  
  // 导出数据
  exportData(): void {
    // 如果正在导出中，则不处理
    if (this.exporting) {
      return;
    }
    
    try {
      // 设置导出状态
      this.exporting = true;
      
      // 定义Excel列配置
      const columns = [
        { header: '序号', key: 'serialNumber', width: 10 },
        { header: '货品编号', key: 'goodsCode', width: 15 },
        { header: '货品名称', key: 'goodsName', width: 20 },
        { header: '货品类型', key: 'goodsType', width: 15 },
        { header: '批次号', key: 'batchNumber', width: 15 },
        { header: '数量', key: 'currentStock', width: 10 },
        { header: '生产日期', key: 'productionDate', width: 15 },
        { header: '过期日期', key: 'expiryDate', width: 15 },
        { header: '仓库', key: 'warehouseName', width: 15 },
        { header: '库位', key: 'locationName', width: 15 },
        { header: '货架期(天)', key: 'shelfLife', width: 12 },
        { header: '状态', key: 'status', width: 12 },
        { header: '剩余天数', key: 'remainingDays', width: 12 },
        { header: '预警天数', key: 'warnDays', width: 12 }
      ];
      
      // 如果当前页数据少于总数，则获取全部数据后再导出
      if (this.dataList.length < this.total) {
        // 准备导出全部数据的查询参数
        let exportParams = new HttpParams()
          .set('SkipCount', '0')
          .set('MaxResultCount', `${this.total}`); // 获取所有数据
        
        // 添加当前查询条件
        Object.keys(this.queryParams).forEach(key => {
          const value = this.queryParams[key as keyof QueryParams];
          if (value !== undefined && value !== null && value !== '' && key !== 'SkipCount' && key !== 'MaxResultCount') {
            exportParams = exportParams.set(key, String(value));
          }
        });
        
        const apiUrl = 'https://localhost:44359/api/app/huo-pin-pi-ci-guan-lian';
        
        // 获取全部数据
        this.http.get<PagedResultDto<HuoPinPiCiGuanLianDto>>(apiUrl, { params: exportParams })
          .subscribe({
            next: async (response) => {
              if (response && response.items && response.items.length > 0) {
                const exportData = response.items.map((item, index) => {
                  const remainingDays = this.calculateRemainingDays(item.expiryDate);
                  return {
                    ...item,
                    serialNumber: index + 1,
                    remainingDays: remainingDays,
                    status: this.getStatus(remainingDays)
                  };
                });
                
                console.log(`获取导出数据成功，共${exportData.length}条记录`);
                // 导出Excel
                await this.excelExportService.exportToExcel(
                  exportData, 
                  '保质期查询',
                  columns
                );
              } else {
                console.warn('没有数据可导出');
                alert('没有数据可导出');
              }
              this.exporting = false;
            },
            error: (error) => {
              console.error('获取导出数据失败:', error);
              
              // 如果API请求失败，尝试导出当前页面数据
              console.log('尝试导出当前页面数据');
              if (this.dataList && this.dataList.length > 0) {
                const exportData = this.dataList.map((item, index) => ({
                  ...item,
                  serialNumber: index + 1
                }));
                
                this.excelExportService.exportToExcel(
                  exportData,
                  '保质期查询',
                  columns
                ).catch(err => {
                  console.error('导出当前页数据失败:', err);
                  alert('导出失败: ' + (err.message || '未知错误'));
                });
              } else {
                alert('没有数据可导出');
              }
              
              this.exporting = false;
            }
          });
      } else {
        // 直接导出当前页数据
        const exportData = this.dataList.map((item, index) => ({
          ...item,
          serialNumber: index + 1
        }));
        
        this.excelExportService.exportToExcel(
          exportData, 
          '保质期查询',
          columns
        ).then(() => {
          console.log('导出成功');
          this.exporting = false;
        }).catch(error => {
          console.error('导出失败:', error);
          alert('导出失败: ' + (error.message || '未知错误'));
          this.exporting = false;
        });
      }
    } catch (error: any) {
      console.error('导出过程出错:', error);
      alert('导出过程出错: ' + (error.message || '未知错误'));
      this.exporting = false;
    }
  }
  
  // 刷新
  refresh(): void {
    this.loadData();
  }
}
